<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Api\MenuRequest;
use App\Models\Menu;
use App\Transformers\MenuTransformer;

class MenuController extends BaseController
{
    /**
     * 一级菜单
     */
    public function menuForMenu()
    {
        $menus = Menu::where('pid', 0)->get();

        return $menus;
    }

    /**
     * 二级菜单
     */
    public function menuForPerm()
    {
        $menus = Menu::where('pid', '<>' , 0)->get();

        return $menus;
    }

    /**
     * 菜单列表
     */
    public function index()
    {
        $menus = cache_menu_all();

        return $this->response->paginator($menus, new MenuTransformer());
    }

    /**
     * 添加菜单
     */
    public function store(MenuRequest $request)
    {
        Menu::create($request->all());

//        刷新缓存
        forget_cache_menu();

        return $this->response->created();
    }

    /**
     * 更新菜单
     */
    public function update(MenuRequest $request, Menu $menu)
    {
        $menu->update($request->all());

//        刷新缓存
        forget_cache_menu();

        return $this->response->noContent();
    }

    /**
     * 删除菜单
     */
    public function destroy(Menu $menu)
    {
        $menu->delete();

//        刷新缓存
        forget_cache_menu();

        return $this->response->noContent();
    }

    /**
     * 菜单状态
     */
    public function status(Menu $menu)
    {
        $menu->status = $menu->status == 0 ? 1 : 0;
        $menu->save();

//        刷新缓存
        forget_cache_menu();

        return $this->response->noContent();
    }
}
